﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using P2PTransmit.Modal;

namespace P2PTransmit.ViewModal.Service
{
    public class TransmitService : ProtocolService<NetworkTask>
    {
        public delegate void UserAcceptFileEventHandler(NetworkTask task);
        public delegate void UserRefuseFileEventHandler(NetworkTask task,TransmitReceiveCode reason);
        public event Func<NetworkTask,int>                                  OnTransmitReceive;
        public event UserAcceptFileEventHandler                             OnUserAccept;
        public event UserRefuseFileEventHandler                             OnUserRefuse;

        public TransmitService(int port) : base( port )
        {
            OnReceive += Filter;
        }

        public new void Dispose()
        {
            started = false;
            base.OnReceive -= Filter;
            base.Dispose();
        }

        private void Filter(string json, IPEndPoint source)
        {
            var protocol = Deserialize<Modal.Protocol.TransmitProtocol>( json );
            if ( protocol.LocalMacAddress == ServiceManager.LocalMacAddress )
                return;
            if(protocol.RemoteMacAddress == ServiceManager.LocalMacAddress)
            {
                if(!protocol.Feedback)
                {
                    protocol.Task.IPAddress = ServiceManager.LocalIPAddress.ToString();
                    protocol.Task.Port = OnTransmitReceive( protocol.Task );
                    protocol.Result = protocol.Task.Port != 0;
                    protocol.Feedback = true;
                    protocol.RemoteMacAddress = protocol.LocalMacAddress;
                    protocol.LocalMacAddress = ServiceManager.LocalMacAddress;
                    Send( Serialize( protocol ) );
                }
                else
                {
                    if(protocol.Result)
                    {
                        OnUserAccept?.Invoke( protocol.Task );
                    }
                    else
                    {
                        OnUserRefuse?.Invoke( protocol.Task, 0 );
                    }
                }
            }
        }

        public void SendRequest(Modal.NetworkTask task,string mac)
        {
            task.State = NetworkState.WaitForAccept;
            var protocol = new Modal.Protocol.TransmitProtocol();
            protocol.LocalMacAddress = ServiceManager.LocalMacAddress;
            protocol.RemoteMacAddress = mac;
            protocol.Feedback = false;
            protocol.Result = false;
            protocol.Task = task;

            Send( Serialize( protocol ) );
        }
    }
}
